package com.szty.libarytest.shotScreen

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import com.szty.libarytest.R
import com.szty.libarytest.other.loge
import kotlinx.android.synthetic.main.activity_shot_screen.*
import java.io.File
import java.io.FileOutputStream

class ShotScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shot_screen)
        wb_test.loadUrl("https://blog.csdn.net/jinfulin/article/details/86016882")
        wb_test.setOnLongClickListener {
            shotScreen()
            return@setOnLongClickListener false
        }
    }
    fun  shotScreen(){
        val filePath =
            "${getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath}/screenShot.png"
        filePath.loge()
        val decorView = window.decorView
        val createBitmap =
            Bitmap.createBitmap(decorView.width, decorView.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(createBitmap)
        decorView.draw(canvas)
        val fileOutputStream = FileOutputStream(filePath)
        createBitmap.compress(Bitmap.CompressFormat.PNG,70,fileOutputStream)
        fileOutputStream.close()
        createBitmap?.recycle()

        refPic(filePath)
    }

    private fun refPic(filePath: String) {
        val file = File(filePath)
//        MediaStore.Images.Media.insertImage(contentResolver,BitmapFactory.decodeFile(file.absolutePath),file.name,null)
        sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
            Uri.fromFile(file)))
    }
}